"""
AI 模型相关路由
"""

from flask import Blueprint, jsonify, current_app
from app.services.ai_service import AIService
from app.utils.decorators import require_api_key
import logging

logger = logging.getLogger(__name__)

models_bp = Blueprint('models', __name__)


@models_bp.route('/models', methods=['GET'])
@require_api_key
def get_models():
    """
    获取可用的 AI 模型列表
    
    响应：
    {
        "success": true,
        "data": [
            {
                "id": "gpt-3.5-turbo",
                "object": "model",
                "created": 1677649963,
                "owned_by": "openai"
            },
            ...
        ]
    }
    """
    try:
        ai_service = AIService()
        result = ai_service.get_available_models()
        
        if result['success']:
            return jsonify(result), 200
        else:
            return jsonify(result), result.get('status_code', 500)
    
    except Exception as e:
        logger.error(f'获取模型列表错误: {str(e)}', exc_info=True)
        return jsonify({
            'success': False,
            'error': '获取模型列表失败',
            'details': str(e)
        }), 500


@models_bp.route('/models/config', methods=['GET'])
@require_api_key
def get_model_config():
    """
    获取当前 AI 配置
    
    响应：
    {
        "success": true,
        "config": {
            "default_model": "gpt-3.5-turbo",
            "default_temperature": 0.7,
            "default_max_tokens": 2000,
            "api_base_url": "https://ai-api.caihc.cn"
        }
    }
    """
    try:
        config = {
            'default_model': current_app.config.get('DEFAULT_MODEL'),
            'default_temperature': current_app.config.get('DEFAULT_TEMPERATURE'),
            'default_max_tokens': current_app.config.get('DEFAULT_MAX_TOKENS'),
            'api_base_url': current_app.config.get('AI_API_BASE_URL'),
            'database_enabled': current_app.config.get('ENABLE_DATABASE')
        }
        
        return jsonify({
            'success': True,
            'config': config
        }), 200
    
    except Exception as e:
        logger.error(f'获取配置错误: {str(e)}', exc_info=True)
        return jsonify({
            'success': False,
            'error': '获取配置失败',
            'details': str(e)
        }), 500

